#pragma once
#include<iostream>
#include"socket.hpp"
#include"epoller.hpp"
#include"connection.hpp"
#include"reactor.hpp"
#include"channel.hpp"

#define MOD EPOLLIN|EPOLLET|EPOLLOUT
//监听器，用于监听客户端的连接请求
class Reactor;
class Channel;
class Listener:public Connection{
    public:
        Listener(uint16_t port):_socket(port){
            _socketfd=_socket.GetFd();
            _socket.Bind(port);
        }
        void Listen(){
            _socket.Listen();
        }
        virtual int Recv(std::string& _inbuffer){
            LOG(ly::LogLevel::INFO)<<"收到客户端连接请求"<<"\n";
            InetAddr* client_addr=new InetAddr;
            int client_fd=_socket.Accept(client_addr);
            //将新链接的socket封装成connection
            Channel* chan=new Channel(client_fd);//添加的channel未指定connection
            Connection* conn=new Connection(client_fd);
            chan->SetConnection(conn);
            //将connection加入到epoll中
            epoll_event enent;
            enent.events=MOD;
            enent.data.fd=client_fd;
            if(_reactor==nullptr){
                LOG(ly::LogLevel::ERROR)<<"Reactor未设置"<<"\n";
                return 0;
            }
            if(_reactor->AddChannel(client_fd,chan,&enent,client_addr)){
                return 1;
            }
            return 0;
        }
        void SetReactor(Reactor* reactor){
            _reactor=reactor;
        }
        virtual bool Send(){
            return false;
        }
        int GetFd(){
            return _socketfd;
        }
    private:
        TcpSocket _socket;
        int _socketfd;
        Reactor* _reactor;//回调epoll
};